package net.caixiaomi.info.base;


import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.View;

import net.caixiaomi.info.R;

import butterknife.Unbinder;
import icepick.Icepick;

import static butterknife.ButterKnife.bind;

/**
 */

public abstract class BaseDialogFragment extends AppCompatDialogFragment {

    @Nullable
    private Unbinder unbinder;

    @LayoutRes
    protected abstract int layoutRes();

    protected abstract void onViewCreated(@NonNull View view);


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.Theme_Dialog);
        if (savedInstanceState != null && !savedInstanceState.isEmpty()) {
            Icepick.restoreInstanceState(this, savedInstanceState);
        }
    }

    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        View contentView = View.inflate(getContext(), layoutRes(), null);
        dialog.setContentView(contentView);
        unbinder = bind(this, contentView);
        onViewCreated(contentView);
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (isAdded()) {
            manager.beginTransaction().remove(this);
        }
        super.show(manager, tag);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) unbinder.unbind();
    }

}
